<template>
  <div class="page-container">
    <div class="content">
  <div style="height:6vh;padding:10px 20px;background-color:#fff;display:flex;justify-content:space-between;align-items:center;">
    <span style="font-size:20px;font-weight:bold;">预约管理</span>
    <el-button type="primary" @click="beforeAdd">新建预约</el-button>
  </div>

  <!-- 新建/编辑预约弹窗 -->
  <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      :before-close="handleClose"
  >
    <el-form
        :model="form"
        label-width="100px"
        label-position="left"
        style="padding:0 20px;"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户" prop="userId" required>
            <el-select
                v-model="form.userId"
                placeholder="请选择用户"
                style="width:100%"
                filterable
            >
              <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="`${user.realName} (${user.phone})`"
                  :value="user.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="陪诊员" prop="escortId" required>
            <el-select
                v-model="form.escortId"
                placeholder="请选择陪诊员"
                style="width:100%"
                filterable
            >
              <el-option
                  v-for="escort in escorts"
                  :key="escort.id"
                  :label="`${escort.realName} (${escort.phone})`"
                  :value="escort.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="服务类型" prop="serviceTypeId" required>
            <el-select
                v-model="form.serviceTypeId"
                placeholder="请选择服务类型"
                style="width:100%"
                @change="handleServiceTypeChange"
            >
              <el-option
                  v-for="type in serviceTypes"
                  :key="type.id"
                  :label="`${type.name} (¥${type.basePrice})`"
                  :value="type.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务费用" prop="totalAmount">
            <el-input v-model="form.totalAmount" disabled>
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="预约时间" prop="appointmentTime" required>
            <el-date-picker
                v-model="form.appointmentTime"
                type="datetime"
                placeholder="选择预约时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width:100%"
                @change="calculateEndTime"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="选择结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width:100%"
                :disabled="!form.serviceTypeId"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactName" required>
            <el-input v-model="form.contactName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone" required>
            <el-input v-model="form.contactPhone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态" prop="status" required>
            <el-select v-model="form.status" placeholder="请选择状态" style="width:100%">
              <el-option label="等待确认预约" value="pending"></el-option>
              <el-option label="即将开启服务" value="confirmed"></el-option>
              <el-option label="服务已完成" value="completed"></el-option>
              <el-option label="已取消" value="cancelled"></el-option>
              <el-option label="已拒绝" value="rejected"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付状态" prop="paymentStatus">
            <el-select v-model="form.paymentStatus" style="width:100%" disabled>
              <el-option label="未支付" value="unpaid"></el-option>
              <el-option label="已支付" value="paid"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span style="flex:1"></span>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </template>
  </el-dialog>
  <!-- 搜索栏 -->
  <el-card style="margin:20px;border-radius:8px;">
    <el-form :inline="true" style="display:flex;align-items:center;gap:15px;">
      <el-form-item label="预约搜索" style="margin-bottom:0;flex:1;">
        <el-input
            placeholder="输入联系人姓名"
            v-model="searchForm.contactName"
            style="width:100%"
        ></el-input>
      </el-form-item>
      <el-form-item style="margin-bottom:0;">
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="findAppointment">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 预约列表 -->
  <el-card style="margin:20px;border-radius:8px;">
    <el-table
        :data="appointments"
        stripe
        style="width:100%"
        header-row-class-name="table-header"
    >
      <el-table-column label="ID" prop="id" width="80" align="center"></el-table-column>
      <el-table-column label="联系人" prop="contactName" align="center"></el-table-column>
      <el-table-column label="联系电话" prop="contactPhone" align="center"></el-table-column>
      <el-table-column label="预约时间" prop="appointmentTime" align="center" width="180"></el-table-column>
      <el-table-column label="结束时间" prop="endTime" align="center" width="180"></el-table-column>
      <el-table-column label="状态" align="center" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ statusMap[row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template #default="{ row }">
          <el-button link type="primary" @click="edit(row.id)">编辑</el-button>
          <el-button
              link
              type="danger"
              @click="del(row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</div>

  <!-- 页脚 -->
  <footer class="app-footer">
    <div class="container">
      <div class="footer-content">
        <p class="footer-title">安心陪诊后台管理系统</p>
        <p class="footer-links">
          &copy; 2025 安心陪诊平台 版权所有 |
          <a href="#" @click.prevent="goToUserAgreement">用户协议</a> |
          <a href="#" @click.prevent="goToPrivacyPolicy">隐私政策</a>
        </p>
      </div>
    </div>
  </footer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import qs from 'qs'
import { ElMessage, ElMessageBox } from 'element-plus'

const BASE_URL = 'http://localhost:8080'

// 数据模型
const dialogVisible = ref(false)
const dialogTitle = ref('新建预约')
const form = ref({
  id: null,
  userId: '',
  escortId: '',
  serviceTypeId: '',
  appointmentTime: '',
  contactName: '',
  contactPhone: '',
  status: ''
})

const searchForm = ref({ contactName: '' })
const appointments = ref([])
const users = ref([])
const escorts = ref([])
const serviceTypes = ref([])

const statusMap = {
  pending: '等待确认预约',
  confirmed: '即将开启服务',
  completed: '服务已完成',
  cancelled: '已取消',
  rejected: '已拒绝'
}

// 加载数据
const loadUsers = () => {
  axios.get(BASE_URL + '/v1/user/select?').then(res => {
    if (res.data.state === 2000) {
      users.value = res.data.data
    }
  })
}
// 加载陪诊员
const loadEscorts = () => {
  axios.get(BASE_URL + '/v1/managerEscort/escorts').then(res => {
    if (res.data.state === 2000) {
      escorts.value = res.data.data
    }
  })
}
// 加载服务类型
const loadServiceTypes = () => {
  axios.get(BASE_URL + '/v1/serviceType/types').then(res => {
    if (res.data.state === 2000) {
      serviceTypes.value = res.data.data
    }
  })
}

// 加载所有预约记录
const loadAppointments = () => {
  let data = qs.stringify(searchForm.value)
  axios.get(BASE_URL + '/v1/appointment/appointments?' + data).then(res => {
    if (res.data.state === 2000) {
      appointments.value = res.data.data
    }
  })
}

// 提交表单
const submitForm = () => {
  const url = form.value.id ? '/v1/appointment/update' : '/v1/appointment/add'
  const postData = {
    ...form.value,
    end_time: form.value.endTime // 确保与后端字段名匹配
  }

  axios.post(BASE_URL + url, postData).then(res => {
    if (res.data.state === 2000) {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      loadAppointments()
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

// 删除预约
const del = (id) => {
  ElMessageBox.confirm('确定删除该预约？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.post(BASE_URL + '/v1/appointment/delete', { id }).then(res => {
      if (res.data.state === 2000) {
        ElMessage.success('删除成功')
        loadAppointments()
      } else {
        ElMessage.error(res.data.msg)
      }
    })
  })
}

// 编辑预约
const edit = (id) => {
  axios.get(BASE_URL + `/v1/appointment/${id}`).then(res => {
    if (res.data.state === 2000) {
      form.value = {
        ...res.data.data,
        endTime: res.data.data.end_time // 确保后端返回的字段名正确
      }
      dialogTitle.value = '编辑预约'
      dialogVisible.value = true
    }
  })
}

// 新增预约
const beforeAdd = () => {
  form.value = {
    id: null,
    userId: '',
    escortId: '',
    serviceTypeId: '',
    appointmentTime: '',
    end_time: '',
    contactName: '',
    contactPhone: '',
    status: '',
    paymentStatus: 'unpaid',
    totalAmount: 0
  }
  dialogTitle.value = '新建预约'
  dialogVisible.value = true
}

// 查询预约记录
const findAppointment = () => {
  const contactName = searchForm.value.contactName.trim(); // 去除前后空格

  if (!contactName) {
    ElMessage.warning("请输入联系人姓名");
    return;
  }

  axios.get(`${BASE_URL}/v1/appointment/contactName`, {
    params: { contactName },
    paramsSerializer: params => {
      return qs.stringify(params, { indices: false });
    }
  })
      .then(res => {
        if (res.data.state === 2000) {
          appointments.value = res.data.data;
          if (appointments.value.length === 0) {
            ElMessage.warning("未找到匹配的预约记录");
          }
        } else {
          ElMessage.error(res.data.message || "查询失败");
        }
      })
      .catch(error => {
        console.error("请求失败：", error);
        ElMessage.error("网络异常，请稍后再试");
      });
}



// 重置搜索框
const resetSearch = () => {
  searchForm.value.contactName = ""
  loadAppointments()
}
// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}

onMounted(() => {
  loadUsers()
  loadEscorts()
  loadServiceTypes()
  loadAppointments()
})


const handleServiceTypeChange = (serviceTypeId) => {
  const selectedType = serviceTypes.value.find(t => t.id === serviceTypeId);
  if (selectedType) {
    form.value.totalAmount = selectedType.basePrice;

    // 自动计算结束时间（示例：假设服务时长为2小时）
    if (form.value.appointmentTime) {
      const startTime = new Date(form.value.appointmentTime);
      const endTime = new Date(startTime.getTime() + 2 * 60 * 60 * 1000);
      form.value.endTime = endTime.toISOString().replace('T', ' ').substring(0, 19);
    }
  } else {
    form.value.totalAmount = 0;
  }
}
// 状态标签类型映射
const getStatusTagType = (status) => {
  const typeMap = {
    pending: 'warning',
    confirmed: 'success',
    completed: '',
    cancelled: 'danger'
    , rejected: 'danger'
  };
  return typeMap[status] || '';
};

// 计算结束时间
const calculateEndTime = () => {
  if (form.value.appointmentTime && form.value.serviceTypeId) {
    const selectedType = serviceTypes.value.find(t => t.id === form.value.serviceTypeId);
    if (selectedType) {
      const startTime = new Date(form.value.appointmentTime);
      const durationHours = selectedType.duration || 2; // 默认2小时
      const endTime = new Date(startTime.getTime() + durationHours * 60 * 60 * 1000);
      form.value.endTime = endTime.toISOString().replace('T', ' ').substring(0, 19);
    }
  }
};
</script>
<style scoped>
/* 表格标题样式 */
.table-header {
  background-color: #f5f7fa;
  font-weight: bold;
}

/* 卡片阴影效果 */
.el-card {
  box-shadow: 0 1px 4px rgba(0,0,0,0.1);
}

/* 弹窗底部按钮居中 */
.el-dialog__footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px 20px;
}

/* 状态标签样式 */
.status-pending {
  color: #e6a23c;
  background-color: #fdf6ec;
  border-color: #f5dab1;
}

.status-confirmed {
  color: #67c23a;
  background-color: #f0f9eb;
  border-color: #e1f3d8;
}

.status-completed {
  color: #409eff;
  background-color: #ecf5ff;
  border-color: #d9ecff;
}

.status-cancelled {
  color: #f56c6c;
  background-color: #fef0f0;
  border-color: #fde2e2;
}

/* 新增的页脚相关样式 */
.page-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.content {
  flex: 1;
  padding-bottom: 20px; /* 为页脚留出空间 */
}

.app-footer {
  background-color: #f5f7fa;
  padding: 10px 0; /* 减小了上下内边距 */
  border-top: 1px solid #e6e6e6;
  margin-top: auto; /* 关键属性，使页脚始终在底部 */
}

.footer-content {
  text-align: center;
}

.footer-title {
  color: #606266;
  margin-bottom: 8px; /* 减小了标题下边距 */
  font-size: 14px; /* 减小了字体大小 */
}

.footer-links {
  color: #909399;
  font-size: 12px; /* 减小了字体大小 */
}

.footer-links a {
  color: #909399;
  transition: color 0.3s;
  margin: 0 5px;
}

.footer-links a:hover {
  color: #a6d2ff;
}
</style>


